package org.monitor.kit;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class IDKit {
	
	private static MessageDigest mdInst = init();
	private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	
	private static MessageDigest init(){
		try {
			return MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
		}
		return null;
	}

	private static String encodeMD5(String s) {
		mdInst.reset();
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public final static String gen() {
		String uuid = UUID.randomUUID().toString();
//		System.out.println(uuid);
		
		long threadId = Thread.currentThread().getId();
//		System.out.println(threadId);
		
		long time = System.nanoTime();
//		System.out.println(time);

		String md5 = encodeMD5(uuid + threadId + time);
//		System.out.println(md5);
		
		String str = cut(md5);
//		System.out.println(str);
		
		return str;
	}
	
	private static String cut(String md5){
		StringBuffer str = new StringBuffer();
			
		for (int i = 0; i < 4; i++) {
			String partStr = md5.substring(i * 8, (i + 1) * 8);
			str.append(partStr.substring(0, 5));
		}
		
		return str.toString();
	}

	public static void main(String[] args) {
		IDKit.gen();
	}

}
